<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>抽奖</title>
    <meta name="viewport" content="width=device-width, user-scalable=0, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="description" content="">
    <link rel="stylesheet" href="__STATIC__/lotto/index.css?v=20220704">
</head>
<body>
<div id="container" class="container">
    <div class="header">
        <div class="header-bg"></div>
    </div>
    <div class="body">
        <div class="award">
            <div class="title"></div>
            <div class="line"></div>
            <div class="notice">
                <div class="icon icon-notice"></div>
                <div class="run-area">
                    <div class="notice-list">
                        {foreach $notice_list as $k => $v}
                        <div class="notice-item">{$v}</div>
                        {/foreach}
                    </div>
                </div>
            </div>
            <div class="award-area">
                <div class="award-box">
                    <!--展示抽奖按钮-->
                    <div class="center-box">
                        <div id="award-btn" class="award-btn"></div>
                        <div class="award-tip">{$price}幸运星抽取一次</div>
                    </div>
                    <!--展示奖项列表-->
                    <div class="award-list">
                        {foreach $award_list as $k => $v}
                        <div class="award-item" data-name="{$v.name}" data-des="{$v.des}" data-img="{$oss}{$v.pic}">
                            <div class="award-bg"></div>
                            <div class="award-img" style="background-image: url({$oss}{$v.img})"></div>
                        </div>
                        {/foreach}
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="footer">
        <div class="footer-bg"></div>
        <div class="star-num">
            <div class="icon icon-star"></div>
            <div class="star-num-des">幸运星：<span id="num">{$star_num}</span></div>
        </div>
    </div>
    <div id="confirm-dialog" class="confirm-dialog">
        <div class="mask"></div>
        <div class="dialog-content">
            <div class="des">你确定要使用{$price}颗幸运星进行抽奖吗？</div>
            <div class="btns">
                <div class="btn" onclick="confirmDialog(0)">取消</div>
                <div id="confirm-yes" class="btn">确定</div>
            </div>
        </div>
    </div>
    <div id="view-dialog" class="view-dialog">
        <div class="mask"></div>
        <div class="view-content">
            <div class="title">查看奖品</div>
            <div class="content">
                <div class="img"></div>
                <div class="name">幸运星x1</div>
                <div class="des">可用于抽奖</div>
            </div>
            <div class="button" onclick="viewDialog(0)">知道了</div>
        </div>
    </div>
    <div id="success-dialog" class="dialog">
        <div class="mask" onclick="successDialog(null, 0)"></div>
        <div class="dialog-content">
            <div class="award-goods-img"></div>
            <div class="award-goods-name">一生报告八折券</div>
            <div id="close-dialog" class="close-btn" onclick="successDialog(this, 0)" data-target="" data-link="">知道了</div>
            <div class="close" onclick="successDialog(null, 0)"></div>
        </div>
    </div>
</div>
{include file="../apps/web/view/public/sensors.html" /}
<script src="https://oss.goddessxzns.com/static/live/js/jquery-1.11.3.min.js"></script>
<script>
    var starNum = parseInt('{$star_num}'), price = parseInt('{$price}'), header = JSON.parse(`{$header}`), oss = `{$oss}`;
    var awardBtn = $('#award-btn'), awardItem = $('.award-item'), index = 0, result, resultIndex, awardTimer1, speed = 400, maxSpeed = 100,
        minSpeed = 500, fast = 3, slow = 0.5;
    // 抽奖按钮添加
    awardBtn.click(function () {
        var _this = $(this)
        if (!_this.hasClass('doing')) {
            // 判断余额是否充足
            if (starNum < price) {
                // 余额不足提示
                toast('幸运星不足' + price + '颗，无法参与抽奖');
                return false;
            }
            // 抽奖确认提示弹窗
            confirmDialog(1);
        } else {
            console.log('已经在抽奖了');
        }
    })
    // 奖品查看详情
    awardItem.click(function () {
        var name = $(this).data('name'), des = $(this).data('des'), img = $(this).data('img');
        console.log(name, des, img)
        $('#view-dialog .content .name').text(name).siblings('.des').text(des).siblings('.img').css({'background-image': 'url(' + img + ')'})
        viewDialog(1);
    })

    /**
     * 确认抽奖
     */
    $('#confirm-yes').click(function () {
        // 隐藏确认弹窗
        confirmDialog(0)
        // 扣减幸运星
        starNum -= price
        $('#num').text(starNum)
        // 请求接口获取抽奖结果
        $.ajax({
            url: '/api/v32/lp/draw',
            type: 'get',
            timeout: 5000,// 5秒超时
            dataType: 'json',
            headers: header,
            data: {},
            beforeSend: function () {
            },
            success: function (res) {
                if (res.code !== 200) {
                    toast(res.msg);
                    return false;
                }
                // 奖品类型 0=>未中奖【下次再来】 1=>卡券 2=>准币 3=>实物 4=>兑换物 5=>幸运星
                // 实物：前往填写地址
                // 幸运星：知道了
                // 卡券：前往卡券中心
                // 装扮：去装扮
                // 准币：前往钱包
                // 下次好运：知道了
                var type = res.data.type, btnText, btnTarget, btnLink;
                result = res.data.id;
                starNum = res.data['lucky_num'];
                switch (type) {
                    case 1://1=>卡券
                        btnText = '前往卡券中心';
                        btnTarget = 'local';
                        btnLink = 'discount_coupon_center?need_auth=2';
                        break;
                    case 2:// 2=>准币
                        btnText = '前往钱包';
                        btnTarget = 'local';
                        btnLink = 'coin_info?need_auth=2';
                        break;
                    case 3:
                        btnText = '前往填写地址';
                        btnTarget = 'local';
                        btnLink = 'lucky_star_record?tab_index=2&need_auth=2';
                        break;
                    case 4:
                        btnText = '去装扮';
                        btnTarget = 'local';
                        btnLink = 'dress_up?tab_index=0&need_auth=2';
                        break;
                    default:
                        btnText = '知道了';
                        btnTarget = '';
                        btnLink = '';
                        break;
                }
                $('#success-dialog').find('.award-goods-img').css({'background-image': 'url(' + oss + res.data['pic'] + ')'}).siblings('.award-goods-name').text(res.data.name).siblings('.close-btn').text(btnText).data('link', btnLink).data('target', btnTarget);
                // 将按钮修改为正在抽奖
                awardBtn.addClass('doing');
                resultIndex = result - 1
                run()
            },
            error: function (err) {
                toast('网络请求异常');
            }
        })

    })

    var noticeItemDom = $('.notice-item'), noticeListDom = noticeItemDom.parent(), noticeTimer;

    init()

    /**
     * 抽奖效果
     */
    function run() {
        var curIndex = index % awardItem.length;
        awardItem.eq(curIndex).addClass('cur').siblings('.award-item').removeClass('cur');
        index++
        if (index >= awardItem.length * fast) {
            // 持续减速
            speed += 35;
        } else {
            // 持续加速
            speed -= 35;
        }
        // 最大最小速度限制
        if (speed > minSpeed) {
            speed = minSpeed;
        } else if (speed < maxSpeed) {
            speed = maxSpeed;
        }
        if (index >= awardItem.length * (fast + slow) && curIndex === resultIndex) {
            // 已中奖
            clearTimeout(awardTimer1)
            awardTimer1 = null
            index = 0
            // 延迟350毫秒展示中奖结果
            setTimeout(function () {
                // 修改按钮为立即抽奖
                awardBtn.removeClass('doing')
                // 弹窗提示中奖信息
                successDialog(null, 1);
                // 修改中奖后的幸运星余额
                $('#num').text(starNum);
            }, 350)
        } else {
            // 自调用
            awardTimer1 = setTimeout(run, speed)
        }
    }

    /**
     * 确认抽奖弹窗
     */
    function confirmDialog(type) {
        var viewDialog = $('#confirm-dialog');
        switch (type) {
            case 1:
                viewDialog.show();
                break;
            default:
                viewDialog.hide();
                break;
        }
    }

    /**
     * 奖品查看弹窗显隐
     */
    function viewDialog(type) {
        var viewDialog = $('#view-dialog');
        switch (type) {
            case 1:
                viewDialog.show();
                break;
            default:
                viewDialog.hide();
                break;
        }
    }

    /**
     * 抽奖完成弹窗显隐
     * @param obj
     * @param type
     */
    function successDialog(obj, type) {
        var successDialog = $('#success-dialog');
        switch (type) {
            case 1:
                successDialog.show();
                break;
            default:
                successDialog.hide();
                // 检测是否需要跳转
                // console.log('target:', $(obj).data('target'), 'link:', $(obj).data('link'))
                var target = $(obj).data('target'), link = $(obj).data('link');
                if (target !== '' && link !== '') {
                    commonJsToNative(target, link);
                }
                break;
        }
    }

    function init() {
        resizeWindow()
        var width = 0;
        noticeItemDom.each(function () {
            width += ($(this).width() + 24)
        })
        console.log('notice list width:', width)
        // 初始化设置中奖用户展示列表的最大宽度
        noticeListDom.width(width);
        // 中奖提示信息横向滚动
        noticeTimer = setInterval(noticeRun, 50)
    }

    $(window).resize(function () {
        resizeWindow();
    })

    function resizeWindow() {
        if ($(window).width() >= 750) {
            $('html').css({'font-size': '32px'});
        } else {
            $('html').css({'font-size': '4.267vw'});
        }
    }

    function noticeRun() {
        var oldLeft = noticeListDom.position().left
        oldLeft -= 1
        if (Math.abs(oldLeft) > noticeListDom.width() + 24) {
            oldLeft = 0
        }
        noticeListDom.css({left: oldLeft})
    }

    function randomNum(minNum, maxNum) {
        switch (arguments.length) {
            case 1:
                return parseInt(Math.random() * minNum + 1, 10);
            case 2:
                return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
            default:
                return 0;
        }
    }

    /**
     * 提示信息
     * @param msg
     */
    function toast(msg) {
        var m = document.createElement('div');
        m.innerHTML = msg;
        m.style.cssText = 'color: #ffffff;background: rgba(0,0,0,0.7);width: 66%;line-height: 2.5rem;text-align: center;border-radius: 0.25rem;position: fixed;top: 50%;left: calc(17% - 16px);z-index: 999999;font-size: 1rem;padding: 0 16px; margin-top: -1.25rem';
        document.body.appendChild(m);
        setTimeout(function () {
            document.body.removeChild(m);
        }, 2500);
    }

    /**
     * 调用客户端本地跳转
     * @param target
     * @param link
     */
    function commonJsToNative(target, link) {
        if (!target) return;
        console.log('commonJsToNative', 'target:', target, 'link:', link, 'app-type:', header['app-type']);
        switch (header['app-type']) {
            case 'ios':
                window.webkit.messageHandlers.commonJsToNative.postMessage({
                    'target': target,
                    'link': link,
                });
                break;
            case 'android':
                androidwebview.commonJsToNative(target, link)
                break;
            default:
                if (target === 'link') {
                    window.location.href = link;
                } else {
                    Log('跳转不支持', 'target:', target, 'link:', link);
                }
        }
    }
</script>
</body>
</html>
